import cv2
import numpy as np

if __name__ == "__main__":
    path = 'image.jpg'
    image_np = cv2.imread(path)
    # print(image_np)
    image_np_gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)
    image_np_gray1 = []
    image_np_c = []
    # print(image_np_gray1)
    for i in range(0, image_np_gray.shape[0]):
        for j in range(0, image_np_gray.shape[1]):
            image_np_gray1.append(image_np_gray[i, j])  # 生成一个全部像素的列表

    # print(image_np_gray1)
    for l in range(0, 256):
        image_np_c.append(image_np_gray1.count(l))  # 计算同一像素个数

    # print(image_np_c)
    U = 0                                           # 像素总值初值
    g = []
    ma = 0
    ma_ = 0
    for h in range(0, 256):
        U += h * image_np_c[h]                      # 计算像素总数
    u = U / sum(image_np_c)                         # 整幅图平均像素值
    # print(u)
    for m in range(0, 256):
        N0 = 0  # 前景像素点数初值
        U0 = 0  # 设置前景总像素初值
        for n in range(0, m+1):
            N0 += image_np_c[n]            # 前景像素个数
            U0 += n * image_np_c[n]                   # 前景像素总值
        # print(U0)
        N1 = sum(image_np_c) - N0                     # 后景像素个数
        # print(N0)
        if N0 != 0 and N1 != 0:
            w0 = N0 / sum(image_np_c)
            w1 = 1 - w0
            u0 = U0 / N0                                 # 计算前景的平均像素值
            u1 = (U - U0) / N1                           # 计算后景的平均像素值
            G = w0 * (u0 - u)**2 + w1 * (u1 - u)**2
            if G > ma:
                ma = G
                ma_ = m
            # g.append(G)
            # print(u0)

    T = ma_

    # 二值化
    thresh = T
    maxval = 255
    # ret, image_np_gray = cv2.threshold(image_np_gray, thresh, maxval, cv2.THRESH_BINARY_INV)
    # print(ret)
    # cv2.imshow('image_np_gray', image_np_gray)
    # cv2.waitKey(0)
    for o in range(0, image_np_gray.shape[0]):
        for p in range(0, image_np_gray.shape[1]):
            if image_np_gray[o, p] <= thresh:
                image_np_gray[o, p] = 0

            else:
                image_np_gray[o, p] = maxval

    cv2.imshow('image_np_gray', image_np_gray)
    cv2.waitKey(0)


